<?php
/**
 * Created by PhpStorm.
 * User: ycp
 * Date: 2019/5/23
 * Time: 22:23
 */

namespace app\api\controller;


use library\Controller;

class WxPay extends Controller
{

    protected $config;
    protected $recordTable = 'lite_coupons_record';
    protected $memberTable = 'store_member';
    public function __construct()
    {
        parent::__construct();
        $this->config = config('wechat.miniapp');
        $host = 'www.huanqiupaozhe.cn';
        $this->host  = 'https://' . $host .'/';
    }

    public function unifiedOrder($order)
    {

        $requestData = [
            'body' => $order['body'],
            'out_trade_no' => $order['order_sn'],
            'total_fee' => $order['price'] * 100,
            'spbill_create_ip' => $this->request->ip(),
            'notify_url' => 'http://www.huanqiupaozhe.cn/api/wx_pay/wxCallback',
            'trade_type' => 'JSAPI',
            'product_id' => $order['activity_id'],
            'openid' => $order['user_id'],
        ];
        try {
            $pay = \We::WePayOrder($this->config);
            $info = $pay->create($requestData);
            if ($info['return_code'] === 'SUCCESS' && $info['result_code'] === 'SUCCESS') {
                return $pay->jsapiParams($info['prepay_id']);
            }
            if (isset($info['err_code_des'])) throw new \think\Exception($info['err_code_des']);
        } catch (\Exception $e) {
            $this->error("创建订单失败参数失败，{$e->getMessage()}");
        }
    }

    public function wxCallback()
    {
        $wechat = \We::WePayOrder($this->config);
        $notify = $wechat->getNotify();
        if ($notify['result_code'] == 'SUCCESS' && $notify['return_code'] == 'SUCCESS') {
            if ($this->update($notify['out_trade_no'], $notify['transaction_id'], $notify['cash_fee'] / 100, 'lite_app')) {
                return $wechat->getNotifySuccessReply();
            }
        } else return $wechat->getNotifySuccessReply();
    }





    public function unifiedOrderCard($order)
    {

        $requestData = [
            'body' => $order['body'],
            'out_trade_no' => $order['order_sn'],
            'total_fee' => $order['price'] * 100,
            'spbill_create_ip' => $this->request->ip(),
            'notify_url' => 'http://www.huanqiupaozhe.cn/api/card/wxCallback',
            'trade_type' => 'JSAPI',
            'product_id' => $order['product_id'],
            'openid' => $order['user_id'],
        ];
        try {
            $pay = \We::WePayOrder($this->config);
            $info = $pay->create($requestData);
            if ($info['return_code'] === 'SUCCESS' && $info['result_code'] === 'SUCCESS') {
                return $pay->jsapiParams($info['prepay_id']);
            }
            if (isset($info['err_code_des'])) throw new \think\Exception($info['err_code_des']);
        } catch (\Exception $e) {
            $this->error("创建订单失败参数失败，{$e->getMessage()}");
        }
    }


    /**
     * 订单状态更新
     * @param string $order_no 订单号
     * @param string $pay_no 交易号
     * @param string $pay_price 交易金额
     * @param string $type 支付类型
     * @return boolean
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function update($order_no, $pay_no, $pay_price, $type = 'wechat')
    {
        $where = ['order_sn' => $order_no, 'pay_status' => '0', 'status' => '2'];
        // 检查订单支付状态
        $order = db('lite_order')->where($where)->find();
        if (empty($order)) return false;

        // 调用会员升级机制
//        Order::update($order['order_no']);
        //更新优惠券使用状态
        if(!empty($order['envelope_id'])){
            $res = db($this->recordTable)->where(['id' => $order['envelope_id']])->update(['status' => 2, 'used_time' => date('Y-m-d H:i:s')]);
            if($res == false){
                return false;
            }
        }
        //如果是使用储值
        if($type == 3){
            $openid = $order['user_id'];
            $result1 = db($this->memberTable)->where(['openid' => $openid])->setInc('use_amount', $pay_price);
            //记录账户余额变化
            $record2 = db('lite_member_amount_record')->insert([
                'open_id' => $openid,
                'type' => 0, //类型(1 加 0 -)
                'price' => $pay_price/$order['count'],
                'count' => $order['count'],
                'total_price' => $pay_price,
                'order_sn' => $order['order_sn'],
                'source_type' => 0, //
                'create_time' => date('Y-m-d H:i;s'),
            ]);
            $record3 =db('lite_order')->where($where)->update([
                'use_card_value' => $pay_price,
                'reduced_price' => $pay_price
            ]);
            if(in_array(false, [$result1, $record2, $record3]) ){
                return false;
            }
        }

        // 更新订单支付状态
        $result = db('lite_order')->where($where)->update([
            'pay_type'  => $type, 'pay_no' => $pay_no, 'status' => '3',
            'pay_price' => $pay_price, 'pay_status' => '1', 'pay_at' => date('Y-m-d H:i:s'),
        ]);
        return $result !== false;
    }

}